package br.com.orion.sga.utils;

import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Properties;

import br.com.orion.sga.exception.FileGenerateException;
import br.com.orion.sga.model.entities.Aluno;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class GenerateCarne {
	
	private static final int PROPRIO_ALUNO = 1;
	private enum PLAINOFPAYMENT {TRIMESTRAL, SEMESTRAL, ANUAL};
	
	private Aluno student;
	private Document document;
	
	private InputStream propertiesFile;
	private Properties sgaProperties;
	
	
	public GenerateCarne(Aluno student) {
		this.student = student;
		document = new Document();
		
		openPropertiesFile();
	}

	/* Load the properties file */
	private void openPropertiesFile() {
		System.out.println(System.getProperty("catalina.base"));
		File file = new File(System.getProperty("catalina.base") + "/webapps/sga/WEB-INF/classes/sga.properties");
		if (propertiesFile == null) {
			try {
				propertiesFile = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		if (sgaProperties == null) {
			sgaProperties = new Properties();
			try {
				sgaProperties.load(propertiesFile);//load properties file
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	public void generateCarne() throws FileGenerateException{
		
		String nameUnderscore = student.getNome().replace(" ", "_");
		String dirCarne = sgaProperties.getProperty("dir_generate_carne");
		
		try {
			
			PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dirCarne + "carne_ " + nameUnderscore + ".pdf"));
			document.open();
			document.addSubject("SGA - Carnê");
			document.addCreator("SGA");
			document.addAuthor("SGA System");
			
			int months = 0;
			if (student.getPlanoPagamento().getDescricao().toUpperCase().equals(PLAINOFPAYMENT.TRIMESTRAL.name())) {
				months = 3;
			} else if (student.getPlanoPagamento().getDescricao().toUpperCase().equals(PLAINOFPAYMENT.SEMESTRAL.name())) {
				months = 6;
			} else if (student.getPlanoPagamento().getDescricao().toUpperCase().equals(PLAINOFPAYMENT.ANUAL.name())){
				months = 12;
			}
			
			int i = 0;
			do {
				
				PdfPTable mainTable = new PdfPTable(2);
				mainTable.setWidthPercentage(90);
				
				
				PdfPCell cellTitle = new PdfPCell();
				cellTitle.setColspan(2);
				
				/* COMPANY NAME */
				Font fontTitle = new Font(Font.TIMES_ROMAN, 25, Font.BOLD);
				Paragraph companyParagraph = new Paragraph();
				companyParagraph.setAlignment(Element.ALIGN_CENTER);
				
				Phrase companyName = new Phrase(student.getEmpresas().getNomeFantasia());
				companyName.setFont(fontTitle);
				companyParagraph.add(companyName);
				
				/* CNPJ */
				Paragraph cnpjParagraph = new Paragraph();
				cnpjParagraph.setAlignment(Element.ALIGN_CENTER);
				Font fontCNPJ = new Font(Font.TIMES_ROMAN, 12, Font.NORMAL);
				cnpjParagraph.setFont(fontCNPJ);
				
				Phrase phraseCompanyCNPJ = new Phrase("CNPJ: " + student.getEmpresas().getCnpj());
				cnpjParagraph.add(phraseCompanyCNPJ);
				
				
				cellTitle.addElement(companyParagraph);
				cellTitle.addElement(cnpjParagraph);
				mainTable.addCell(cellTitle);
				
				//--------------------------------------------
				
				/* STUDENT DATA */
				PdfPCell cellStudentData = new PdfPCell();
				//cellStudentData.setBorder(1);
				cellStudentData.setColspan(2);
				
				/* STUDENT NAME */
				Paragraph studentDataParagraph = new Paragraph();
				studentDataParagraph.setAlignment(Element.ALIGN_LEFT);
				
				Phrase studentNamePhrase = new Phrase("ALUNO: " + student.getNome().toUpperCase());
				studentDataParagraph.add(studentNamePhrase);
				cellStudentData.addElement(studentDataParagraph);
				
				if (student.getResponsavel().getId() != PROPRIO_ALUNO) {
					
					Paragraph studentDataNameReponsibleParaghraph = new Paragraph();
					studentDataNameReponsibleParaghraph.setAlignment(Element.ALIGN_LEFT);
					Phrase responsibleNamePhrase = new Phrase("RESPONSÁVEL: " + student.getResponsavel().getNome().toUpperCase());
					studentDataNameReponsibleParaghraph.add(responsibleNamePhrase);
					
					Paragraph studentDataCPFReponsibleParaghraph = new Paragraph();
					studentDataCPFReponsibleParaghraph.setAlignment(Element.ALIGN_LEFT);
					Phrase responsibleCPF = new Phrase("CPF DO RESPONSÁVEL: " + student.getResponsavel().getCpf());
					studentDataCPFReponsibleParaghraph.add(responsibleCPF);
					
					cellStudentData.addElement(studentDataNameReponsibleParaghraph);
					cellStudentData.addElement(studentDataCPFReponsibleParaghraph);
					
				} else {
					
					Paragraph studentDataCPFStudentParaghraph = new Paragraph();
					studentDataCPFStudentParaghraph.setAlignment(Element.ALIGN_LEFT);
					
					Phrase studentCPF = new Phrase("CPF: " + student.getCpf());
					
					studentDataCPFStudentParaghraph.add(studentCPF);
					
					cellStudentData.addElement(studentDataCPFStudentParaghraph);
				}
				
				mainTable.addCell(cellStudentData);
				
				//----------------------------------------------------
				
				/* VALUES DATA */
				PdfPCell cellValues = new PdfPCell();
				cellValues.setColspan(2);
				
				Paragraph vencimentoParagraph = new Paragraph();
				vencimentoParagraph.setAlignment(Element.ALIGN_LEFT);
				
				Phrase phraseVencimento = new Phrase("Vencimento: " + generateVencimentoDate(student.getVencimento().getDia(), i));
				vencimentoParagraph.add(phraseVencimento);
				
				
				Paragraph valueParagraph = new Paragraph();
				valueParagraph.setAlignment(Element.ALIGN_LEFT);
				
				Phrase phraseValue = new Phrase("Valor: " + student.getValorMensalidade());
				valueParagraph.add(phraseValue);
				
				Paragraph valuePersonalParagraph = new Paragraph();
				valuePersonalParagraph.setAlignment(Element.ALIGN_LEFT);
				
				Phrase phraseValuePersonal = new Phrase("Valor do Personal: " + student.getValorPersonal());
				valuePersonalParagraph.add(phraseValuePersonal);
				
				Paragraph valueTotalParagraph = new Paragraph();
				valueTotalParagraph.setAlignment(Element.ALIGN_LEFT);
				
				Phrase phraseValueTotal = new Phrase("Total: R$ " + getTotalValue());
				valueTotalParagraph.add(phraseValueTotal);
				
				cellValues.addElement(vencimentoParagraph);
				cellValues.addElement(valueParagraph);
				cellValues.addElement(valuePersonalParagraph);
				cellValues.addElement(valueTotalParagraph);
				
				mainTable.addCell(cellValues);
				
				//------------------------------------------------
				mainTable.setSpacingAfter(10);
				
				document.add(mainTable);
				
				
				i++;
			} while (i < months);
			
		} catch (FileNotFoundException e) {
			throw new FileGenerateException("Falha ao criar o carnê!");
		} catch (DocumentException e) {
			throw new FileGenerateException("Falha ao criar o carnê!");
		}
		
		document.close();
		
		File filePrintout = new File(dirCarne + "carne_ " + nameUnderscore + ".pdf");
		try {
			Desktop.getDesktop().open(filePrintout);
		} catch (IOException e) {
			throw new FileGenerateException("Falha ao abrir o carnê gerado!");
		}
	}

	
	
	
	private float getTotalValue() {
		return student.getValorMensalidade() + student.getValorPersonal();
	}


	private String generateVencimentoDate(Integer dia, int contMonth) {
		Calendar calendar = Calendar.getInstance();

		if  (((calendar.get(Calendar.MONTH) + 1) + contMonth) > 12) {
			int year = calendar.get(Calendar.YEAR) + 1;
			int month = (((calendar.get(Calendar.MONTH) + 1) + contMonth) - 12);
			if (month < 10)
				return dia + "/0" + month + "/" + year;
			else
				return dia + "/" + month + "/" + year;
		} 
		return dia + "/" + ((calendar.get(Calendar.MONTH) + 1) + contMonth) + "/" + calendar.get(Calendar.YEAR);
	}


	public Aluno getStudent() {
		return student;
	}

	public void setStudent(Aluno student) {
		this.student = student;
	}
	
	public Document getDocument() {
		return document;
	}
	
	public void setDocument(Document document) {
		this.document = document;
	}
	
	

}
